package com.leicx.guli.common.utils;

import com.google.common.base.Strings;
import com.leicx.guli.common.exception.RRException;

import java.util.ArrayList;
import java.util.List;

/**
 * @author daxiong
 * @date 2021/8/16 下午10:15
 */
public class FeignUtil {

    public static <T> T formatClass(R r, Class<T> tClass) {
        return formatClass(r, "data", tClass);
    }

    public static <T> T formatClass(R r, String key, Class<T> tClass) {
        String jsonString = getResultJson(r, key);
        if (Strings.isNullOrEmpty(jsonString)) {
            return null;
        }
        return JsonUtil.parseObject(jsonString, tClass);
    }

    private static String getResultJson(R r, String key) {
        if (!r.success()) {
            throw new RRException(r.get("msg").toString());
        }
        return JsonUtil.toJsonString(r.get(key));
    }

    public static <T> List<T> formatListClass(R r, Class<T> tClass) {
        return formatListClass(r, "data", tClass);
    }

    public static <T> List<T> formatListClass(R r, String key, Class<T> tClass) {
        String jsonString = getResultJson(r, key);
        if (Strings.isNullOrEmpty(jsonString)) {
            return new ArrayList<>();
        }
        return JsonUtil.parseList(jsonString, tClass);
    }
}
